var rate = '';
var laypage = '';
var this_company_id = '';

var PAGES = {
	init:function(){
		layui.use(function() {
			rate = layui.rate;
			laypage = layui.laypage;
			var util = layui.util;
			var form = layui.form;
			
			// 事件 处理 新增和纠错功能的
			util.on('lay-on', {
				
				'chtypes':function(e){
					console.log(e)
					e.siblings('.nac_mkd').removeClass('actives')
					e.addClass('actives')
					var ids = e.attr('data-comid');
					var d   = e.closest('.productDescription');
					d.find('.ulmjds').hide()
					d.find('[data-comid="'+ids+'"]').show()
				},
				
			   'tips-photos-one': function(e){
					var url = e.attr('src')
					layer.photos({
						photos: {
						  "title": "大图查看",
						  "start": 0,
						  "data": [{"pid": 5,"src": url,}]
						},
						footer: false
					});
				},
			   'test-page-custom': function(e){
					var  this_id   = e.attr('data-id');
					var  this_type = e.attr('data-type');
					
					layer.open({
					  type: 1,
					  scrollbar:false,
					  area: '600px',
					  resize: false,
					  shadeClose: true,
					  title: [this_type == 0 ? '内容新增填写' : '内容纠错填写', 'font-size:16px;font-weight: 600'],
					  content: `
						<div class="layui-form" lay-filter="filter-test-layer" style="margin: 20px 16px 16px 16px;">
						  <div class="demo-login-container">
						  
							<div class="layui-form-item">
							  <div class="layui-input-wrap">
								<textarea name="content" value="" style="min-height: 165px;" lay-verify="required" placeholder="请填写内容" lay-reqtext="请填写内容" autocomplete="off" class="layui-textarea" lay-affix="clear"></textarea>
							  </div>
							</div>
							
							<div class="layui-form-item" style="margin-top:20px;display: flex;align-items: center;justify-content: flex-end;">
								<button style="width:100px" class="layui-btn" lay-submit lay-filter="demo-login">提交</button>
							</div>
						   
						  </div>
						</div>
					  `,
					  success: function(){
						// 对弹层中的表单进行初始化渲染
						form.render();
						
						// 表单提交事件
						form.on('submit(demo-login)', function(data){
						  var field = data.field; // 获取表单字段值
						  field.content_id = this_id;
						  field.type = this_type;
						  field.url  = window.location.href;
						  setPageCorrect(field)
						  return false; // 阻止默认 form 跳转
						});
					}
				});
			}
							  
			})
			
			
			this_company_id = wxx.getParam() ? wxx.getParam().id : localStorage.getItem("jingjiang_company_id");
			
		
			// 完整显示
			laypage.render({
				elem: 'demo-laypage-all', // 元素 id
				count: 100, // 数据总数
				layout: ['prev', 'page', 'next', 'skip', 'count', ], // 功能布局
				prev: '<em>←</em>',
				next: '<em>→</em>',
				jump: function(obj) {
		
				}
			});
		
		
		});
	},
	
	getCompanyData:function(page) {
		this_company_id = wxx.getParam() ? wxx.getParam().id : localStorage.getItem("jingjiang_company_id");
		var datas = {
			url: '/api/brand/detail',
			http_type: 'POST',
			datas: {id: this_company_id}
		}
		wxx.HttpReqeust(datas, function(ret) {
			if (ret.code == 1) {
				
				switch (page){
					case 'index':
						if($('#pageContent').length){
							var html = template('pageContentScript', ret.data);
							$("#pageContent").empty().append(html);
							
						}
						if($('#rightDatas').length){
							var html2 = template('rightDatasScript', ret.data);
							$("#rightDatas").empty().append(html2);
							
						}
						if($('#SHOW_TYPE2').length){
							var html3 = template('SHOW_TYPE_SCRIPT2', ret.data);
							$("#SHOW_TYPE2").empty().append(html3);
						}
						
						
						// 各个介绍等开始请求
						document.title = ret.data.name
						PAGES.HomePage(ret.data.type)
						// 评分处理
						initRate();
						break;
					case 'industry_introduction':
						PAGES.industry_introduction(ret.data)
						break;
					case 'partner':
						PAGES.partnerData(ret.data)
						break;	
				}
			}
		});
	},
	
	
	//  获取 公司介绍 || 品牌故事 || 布局情况
	HomePage:function(type){
		this_company_id = wxx.getParam() ? wxx.getParam().id : localStorage.getItem("jingjiang_company_id");
		//账号类型：0.主账号，1.产品子账号，2.行业子账号，3.技术子账号
		var keysets = [];
		switch (type*1){
			case 0:
				keysets = [
					{keyset:'cmh_intro',name:'公司介绍',navStyle:1,textType:'text',companyType:type,AnchorPoint:'k_gsjs'},
					{keyset:'cmh_story',name:'品牌故事',navStyle:1,textType:'text',companyType:type,AnchorPoint:'K_ppgs'},
					{keyset:'cmh_layout',name:'布局情况',navStyle:1,textType:'layout',companyType:type,AnchorPoint:'k_bjqk'},
				]
				break;
			case 1:
				keysets = [
					{keyset:'pdh_intro',name:'产品介绍',navStyle:2,textType:'text',companyType:type,AnchorPoint:'k_cpjs'},
					{keyset:'pdh_honor',name:'资质与荣誉',navStyle:2,textType:'imgList',companyType:type,AnchorPoint:'k_zzry'},
					{keyset:'pdh_layout',name:'布局情况',navStyle:2,textType:'layout',companyType:type,AnchorPoint:'k_bjqk'},
				]
				break;
			case 2:
				keysets = [
					{keyset:'inh_intro',name:'行业介绍',navStyle:2,textType:'text',companyType:type,AnchorPoint:'k_hyjs'},
					{keyset:'inh_honor',name:'资质与荣誉',navStyle:2,textType:'imgList',companyType:type,AnchorPoint:'k_zzry'},
					{keyset:'inh_layout',name:'布局情况',navStyle:2,textType:'layout',companyType:type,AnchorPoint:'k_bjqk'},
				]
				break;	
			case 3:
				keysets = [
					{keyset:'teh_intro',name:'技术介绍',navStyle:2,textType:'text',companyType:type,AnchorPoint:'k_jsjs'},
					{keyset:'teh_honor',name:'资质与荣誉',navStyle:2,textType:'imgList',companyType:type,AnchorPoint:'k_zzry'},
					{keyset:'teh_layout',name:'布局情况',navStyle:2,textType:'layout',companyType:type,AnchorPoint:'k_bjqk'},
				]
				break;		
		}
		
		
		//  获取 上述请求合集  保证请求顺序 按照 循环顺序	
		PAGES.fetchSequentially(keysets).then(results => {
			for (var i = 0; i < results.length; i++) {
				var html = template('publicDataScript', results[i]);
				$("#publicData").append(html);
			}
			//  处理下图片 实现大图查看
			$('.productDescription img').each(function(){
				var url = $(this).attr('src');
				$(this).addClass('fancybox').attr('data-fancybox-group','gallery').attr('href',url).attr('title','点击查看大图').attr('lay-on','tips-photos-one')
			})
			
			//  首页描点处理
			PAGES.AnchorPointFun();
			 
		});
		
	},
	
	
	//  首页描点处理
	AnchorPointFun:function(){
		$('#SHOW_TYPE2').on('click','.lis_item .t_name',function(){
			var ids = $(this).attr('data-id');
			$('.t_name').removeClass('thisActive')
			$(this).addClass('thisActive')
			document.querySelector('#'+ids).scrollIntoView({
			  behavior: "smooth", // 定义动画过渡效果， "auto"或 "smooth" 之一。默认为 "auto"
			  block: "center",    // 定义垂直方向的对齐， "start", "center", "end", 或 "nearest"之一。默认为 "start"
			  inline: "nearest"   // 定义水平方向的对齐， "start", "center", "end", 或 "nearest"之一。默认为 "nearest"
			})
		})
	},
	
	
	fetchSequentially:function(urls) {
	    var results = [];
	    var deferred = $.Deferred();
	    var promise = deferred.resolve().promise(); // 初始的 resolved Promise
		
		$.each(urls, function(index, v) {
		     promise = promise.then(function() {
		         return $.ajax({
		            url: wxx.urls()+'/api/page',
		            method: 'POST',
					data:{
						relate_id: this_company_id,
						keyset:v.keyset
					},
		            dataType: 'json',
					headers: {
					 	"token": localStorage.getItem("jingjiang_token") ? localStorage.getItem("jingjiang_token") : ''
					},
		         }).then(function(data) {
					 //  自定义数据带入
					data.data.pages = v; 
		            results.push(data.data);
		         }).fail(function(error) {
		             console.error('Failed to fetch ' + url + ':', error);
		         });
		     });
		});
		
		return promise.then(() => results); 
	},
		
	
	//  废弃 方法
	getPageContent:function(v){
		var datas = {
			url: '/api/page',
			http_type: 'POST',
			datas: {
				relate_id: this_company_id,
				keyset:v.keyset
			}
		}
		wxx.HttpReqeust(datas, function(ret) {
			if (ret.code == 1) {
				//  自定义数据带入
				ret.data.pages = v; 
				var html = template('publicDataScript', ret.data);
				$("#publicData").append(html);
				
				$('.productDescription img').each(function(){
					var url = $(this).attr('src');
					$(this).addClass('fancybox').attr('data-fancybox-group','gallery').attr('href',url).attr('title','点击查看大图').attr('lay-on','tips-photos-one')
				})
		
			}
		});
	},
	
	
	
	
	// 企业介绍 传入 v.type 区分 主账号 子账号等
	industry_introduction:function(v){
		//type 账号类型：0.主账号，1.产品子账号，2.行业子账号，3.技术子账号
		var type = v.type
		switch (type){
			case 0:
				document.title ='企业介绍'
				getCompanyMore('cm_intro',v);
				break;
			case 1:
				document.title ='产品及解决方案'
				getCompanyMore('pd_product',v);
				break;
			case 2:
				document.title ='行业解决方案'
				getCompanyMore('in_industry',v);
				break;	
			case 3:
				document.title ='技术解决方案'
				getCompanyMore('te_solution',v);
				break;		
		}
	},
	
	// 客户合作伙伴 数据 v.type 区分 主账号 子账号等
	partnerData:function(v){
		var type = v.type
		switch (type){
			case 0:
				getCompanyMore('cm_parter',v);
				break;
			case 1:
				getCompanyMore('pd_customer',v);
				break;
			case 2:
				getCompanyMore('in_partner',v);
				break;	
			case 3:
				getCompanyMore('te_partner',v);
				break;		
		}
	},
	
	
	
}




// 提交 新增和纠错
function setPageCorrect(obj){
	var datas = {
		url  :'/api/page/correct', 
		http_type:'POST',
		loading:true,
		datas:obj
	}
	wxx.HttpReqeust(datas,function(ret){
		layer.alert(ret.msg,{
			title:'温馨提示',
		},function(){
			console.log(ret)
			if(ret.code == 1){
				layer.closeAll()
			}else{
				layer.closeLast(); 
			}
		});
		
	});
}
	

//  获取多个账户类型  介绍 || 合作伙伴  数据
function getCompanyMore(keyset,v){
	var datas = {
		url: '/api/page',
		http_type: 'POST',
		datas: {
			relate_id: this_company_id,
			keyset:keyset
		}
	}
	wxx.HttpReqeust(datas, function(ret) {
		if (ret.code == 1) {
			ret.data.company = v; // 追加公司数据
			console.log(ret.data)
			//  介绍内容渲染
			var html = template('pageComScript', ret.data);
			$("#pageCom").empty().append(html);
			
			// 左侧锚点导航渲染
			var html2 = template('addComyScript', ret.data);
			console.log(ret.data)
			$("#addComy").empty().append(html2);
			
			//  调用一下公共分类展开收起等方法
			wxx.init_types(true);
			
			
			$('.productDescription img').each(function(){
				var url = $(this).attr('src');
				$(this).addClass('fancybox').attr('data-fancybox-group','gallery').attr('href',url).attr('title','点击查看大图').attr('lay-on','tips-photos-one')
			})
	
		}
	});
}


function initRate() {
	// 总评分
	rate.render({
		elem: '#allStar',
		setText: function(value) {
			this.span.text((value * 1) + '分');
		}
	});
	// 批量渲染
	rate.render({
		elem: '.class-test-rate',
		setText: function(value) {
			this.span.text((value * 2) + '分');
		}
	});
}


PAGES.init()